package com.example.registration.controller;

import com.example.registration.entity.Registration;
import com.example.registration.service.RegistrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/")
public class RegistrationController {

    private static final String REGISTRATION_COOKIE_NAME = "registration_completed";

    @Autowired
    private RegistrationService registrationService;

    @GetMapping("/a")
    public String index(HttpServletRequest request) {
        // 检查是否已报名，如果已报名则重定向到成功页面
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (REGISTRATION_COOKIE_NAME.equals(cookie.getName()) && "true".equals(cookie.getValue())) {
                    return "redirect:/success";
                }
            }
        }
        return "redirect:/register-form";
    }

    @GetMapping("/register-form")
    public String showRegistrationForm(HttpServletRequest request, Model model) {
        // 检查是否已报名，如果已报名则重定向到成功页面
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (REGISTRATION_COOKIE_NAME.equals(cookie.getName()) && "true".equals(cookie.getValue())) {
                    return "redirect:/success";
                }
            }
        }
        model.addAttribute("registration", new Registration());
        return "registration";
    }

    @PostMapping("/register")
    @ResponseBody
    public Map<String, Object> register(@Valid Registration registration, BindingResult bindingResult, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>();

        // 验证输入
        if (bindingResult.hasErrors()) {
            result.put("success", false);
            result.put("message", "表单验证失败：" + bindingResult.getAllErrors().get(0).getDefaultMessage());
            return result;
        }

        try {
            // 调用服务层保存报名信息并获取结果
            Map<String, Object> serviceResult = registrationService.saveRegistration(registration);
            result.putAll(serviceResult);

            // 只有当报名成功时才设置Cookie
            if (Boolean.TRUE.equals(serviceResult.get("success"))) {
                // 设置用户联系方式的Cookie，用于识别已经报名的用户
                Cookie phoneCookie = new Cookie("user_phone", registration.getContactPhone());
                phoneCookie.setMaxAge(60 * 60 * 24 * 30); // 30天有效期
                phoneCookie.setPath("/");
                response.addCookie(phoneCookie);

                // 设置报名完成的Cookie
                Cookie registrationCookie = new Cookie(REGISTRATION_COOKIE_NAME, "true");
                registrationCookie.setMaxAge(60 * 60 * 24 * 30); // 30天有效期
                registrationCookie.setPath("/");
                response.addCookie(registrationCookie);

                // 添加重定向URL
                result.put("redirectUrl", "/success");
            }

            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            return result;
        }
    }

    @GetMapping("/success")
    public String showSuccessPage(Model model, HttpServletRequest request, HttpServletResponse response) {
        // 检查是否有报名完成的Cookie
        boolean hasRegistrationCookie = false;
        // 从Cookie中获取用户联系方式
        Cookie[] cookies = request.getCookies();
        String contactPhone = null;

        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (REGISTRATION_COOKIE_NAME.equals(cookie.getName()) && "true".equals(cookie.getValue())) {
                    hasRegistrationCookie = true;
                }
                if ("user_phone".equals(cookie.getName())) {
                    contactPhone = cookie.getValue();
                }
            }
        }
        // 如果没有报名完成Cookie，重定向到报名页面
        if (!hasRegistrationCookie) {
            return "redirect:/a";
        }
        if (contactPhone == null) {
            // 创建一个新的cookie用于删除旧的cookie
            Cookie toDelete = new Cookie(REGISTRATION_COOKIE_NAME, "false");
            toDelete.setMaxAge(0); // 设置最大生命周期为0，表示删除该cookie
            toDelete.setPath(cookies[0].getPath()); // 确保路径与要删除的cookie相同
            response.addCookie(toDelete); // 将新cookie添加到响应中，以覆盖旧cookie
            return "redirect:/a";
        }
        // 如果没有找到联系方式Cookie，重定向到报名页面
        Registration registration = registrationService.getRegistrationByContactPhone(contactPhone);
        if (registration == null) {
            // 创建一个新的cookie用于删除旧的cookie
            Cookie toDelete = new Cookie(REGISTRATION_COOKIE_NAME, "false");
            toDelete.setMaxAge(0); // 设置最大生命周期为0，表示删除该cookie
            toDelete.setPath(cookies[0].getPath()); // 确保路径与要删除的cookie相同
            response.addCookie(toDelete); // 将新cookie添加到响应中，以覆盖旧cookie
            return "redirect:/a";
        }
        // 将报名信息添加到模型中
        model.addAttribute("registration", registration);
        return "success";
    }
}